package com.monitor.zkm.core.listener;

import bean.HostStatus;
import com.monitor.zkm.dao.HostStatusRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class PathAgentListener implements PathChildrenCacheListener {

    private Map<String, HostStatus> nodeBeanMap = new HashMap<>();

    private HostStatusRepository hostStatusRepository;


    public PathAgentListener(HostStatusRepository hostStatusRepository){
        this.hostStatusRepository = hostStatusRepository;
    }

    @Override
    public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
        ChildData childData = event.getData();
        if(childData == null){
            log.error("childData is null");
            return;
        }
        String path = childData.getPath();
        HostStatus status = nodeBeanMap.get(path);
        if(status == null){
            status = hostStatusRepository.findHostStatusByNodePath(path);
            nodeBeanMap.put(path,status);
        }
        if(event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ){
            log.info("新增节点：{}",path);
            if(status == null){
                status = new HostStatus();
                status.setHostIP(new String(childData.getData(), RemotingHelper.DEFAULT_CHARSET));
                status.setNodePath(path);
                if(hostStatusRepository.save(status) != null){
                    nodeBeanMap.put(path,status);
                }
            }else{
                status.setStat("运行");
                hostStatusRepository.save(status);
            }
        }else if(event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED){
            log.info("节点丢失：{}",path);
            try {
                status.setStat("停止");
                hostStatusRepository.save(status);
                nodeBeanMap.remove(path);
            }catch (Exception e){
                log.error("删除失败：{}",e.getMessage());
            }
        }
    }
}
